<?php
	require('../Model/mysql.php');
	require('../host_config.php');
	include_once '../Model/GCM.php';

	$mysql = new MySQL();
    $link = $mysql->connect($mysql_host, $mysql_user, $mysql_passwd, $mysql_db);
    $shopid = $mysql->real($_POST["shopid"]);         //店家編號
    $clientname = $mysql->real($_POST["clientname"]); //客戶名稱
    $orderofnum = $mysql->real($_POST["orderofnum"]); //訂位人數
    $cellphone = $mysql->real($_POST["cellphone"]);
    $queue = $mysql->real($_POST["queue"]); //判斷要不要queue的flag
    $imsi = $mysql->real($_POST["imsi"]);
    $gcm_regid = $mysql->real($_POST["gcm_regid"]);
    /*
	$ShopName = $_POST["ShopName"];
  	$ShopName = mysql_real_escape_string($ShopName);
	$clientName = $_POST["clientName"];
    $clientName = mysql_real_escape_string($clientName);
	$PeoNumber = $_POST["PeoNumber"];
    $PeoNumber = mysql_real_escape_string($PeoNumber);
	$clientPhone = $_POST["clientPhone"];
	$clientPhone = mysql_real_escape_string($clientPhone);
	$queue = $_POST["quene"];
	$queue = mysql_real_escape_string($queue);
	$imsi = $_POST["imsi"];
	$imsi = mysql_real_escape_string($imsi);
	$gcm_regid = $_POST["reg_id"];
	$gcm_regid = mysql_real_escape_string($gcm_regid);
	*/


	if ($shopid != NULL && $clientname != NULL && $orderofnum != NULL && $cellphone != NULL && $queue != NULL && $imsi != NULL && $gcm_regid != NULL) {
		$str1 = '重複訂位，訂位取消';
		$CheckTime = date("Y-m-d H:i");
		$str3 = '訂位人數已達上限，無法訂位';
		$str4 = '約需等待20分鐘';	// watting time 20 mins
		$str5 = '請於10分鐘內到店';	// watting time 10 mins
		$temp = 0;                  //
		//$queue = '排隊';
		//$sql = "select clientPhone from client where ShopName = '$ShopName'";
		//檢查次客戶有沒有對同意間餐廳重複定位
		//$sql = "select imsi from client where ShopName = '$ShopName'";
		$sql = "SELECT imsi FROM Client WHERE shopid = '$shopid'";
		$result = mysql_query($sql, $link) or die("Execute SQL command failed!");
		while ($row = mysql_fetch_row($result)) {
			//if ($clientPhone == $row[0]) {
			if ($imsi == $row[0]) {
				print_r($str1);
				$temp = 1;
				break;
			}
		}
		//檢查客戶定位的人數有沒有超過餐廳的剩餘定位數量
		//$sql =  "select max_number, current from android where all_name = '$ShopName'";
		//$number = $mysql->query_row($sql, $link);
		//if ($number[1] + $PeoNumber > $number[0])
		//	$queue = 1;
		//進行訂位
		if ($temp == 0) {
			if ($queue == 0) {
				$count = 0;
				//計算此使用者在系統內訂位的數量，如果超過三次就不可以訂位
				//$sql = "select * from client where imsi = '$imsi'";
				$sql = "SELECT * FROM Client WHERE imsi = '$imsi'";
				$result = $mysql->query($sql, $link);
                while($e=mysql_fetch_assoc($result))
                	$count++;
                //取得店家的相關資訊：最大定位數量、目前使用人數、店家id
				//$sql = "SELECT max_number, current, id FROM android WHERE all_name = '$ShopName'";
                $sql = "SELECT maxofnumber, currentnumber FROM Shops WHERE shopid = '$shopid'";
		        $query = mysql_query($sql, $link) or die ("Execute sql query fail!!");
       		 	$row = mysql_fetch_row($query);
      	 	 	$maxofnumber = $row[0];
        		$currentnumber = $row[1];
        		//$id = $row[2];
				if ($count > 3) {
					//訂位超過三次，不可以訂位
					print_r('滿三次');
				} else {
					//訂位程序
					if ($maxofnumber - $currentnumber < 1) {
						//print_r($str4);
						// GCM alert
						$gcm = new GCM();

						$registatoin_ids = array($gcm_regid);
						$message = array("price" => $str4);

						$result = $gcm->send_notification($registatoin_ids, $message);

					}
					//else if ($maxofnumber - $currentnumber < $PeoNumber) {
					else if ($maxofnumber - $currentnumber < $orderofnum) {
						//print_r($str4);
					    // GCM alert
						$gcm = new GCM();

						$registatoin_ids = array($gcm_regid);
						$message = array("price" => $str4);

						$result = $gcm->send_notification($registatoin_ids, $message);

					}else {
	               		//$currentnumber = $currentnumber + $PeoNumber;
						$currentnumber = $currentnumber + $orderofnum;
 		        		//$sql = "UPDATE android SET current = '$currentnumber' WHERE id = '$id'";
 		        		$sql = "UPDATE Shops SET currentnumber = '$currentnumber' WHERE shopid = '$shopid'";
        	    		$query = mysql_query($sql, $link) or die ("Execute rquery fail!!");
						//print_r($str5);
               			//$sql = "INSERT INTO client VALUES (NULL, '$ShopName', '$clientName', '$PeoNumber', '$clientPhone', '$CheckTime', '$imsi', '$gcm_regid')";
               			//先將arrivetime=NULL與flag設定為0
        	    		$sql = "INSERT INTO Client VALUES (NULL, '$shopid', '$clientname', '$orderofnum', '$cellphone', '$CheckTime', NULL, '$imsi', '$gcm_regid', 0)";
              			$result = mysql_query($sql, $link) or die ("Execute SQL command failed!");

              			// GCM alert
              			$gcm = new GCM();

              			$registatoin_ids = array($gcm_regid);
              			$message = array("price" => $str5);

              			$result = $gcm->send_notification($registatoin_ids, $message);

					}
				}
			} else {

          //echo $row[0].' '.$row[1];
          //die();

        //##############origin code#############//
        //先不處理超過八人
        //需要進行排隊步驟
        //$sql = "INSERT INTO queue VALUES (NULL, '$ShopName', '$clientName', '$PeoNumber', '$clientPhone', '$CheckTime', '$imsi', '$gcm_regid')";
        //先將arrivetime=NULL與flag設定為-1
        //$sql = "INSERT INTO Client VALUES (NULL, '$shopid', '$clientname', '$orderofnum', '$cellphone', '$CheckTime', NULL, '$imsi', '$gcm_regid', -1)";
        //$result = $mysql->query($sql, $link);
        //##############origin code#############//
				//$queue = 20;
				//print_r($queue);

				// GCM alert
				$gcm = new GCM();
				$registatoin_ids = array($gcm_regid);
				$message = array("price" => $str4);
				$result = $gcm->send_notification($registatoin_ids, $message);
			}
		}else
			die();
	}else {
		echo "<script language='javascript'>";
        echo "alert('You have no permission to read this page!');";
		echo "history.back();";
		echo "</script>";
		header("location:../login.php");
	}
?>
